package com.ysw.rpc.server.handler.inbound;

import com.ysw.rpc.common.messages.Request;
import com.ysw.rpc.server.annotatiaon.RpcService;
import com.ysw.rpc.server.component.ApplicationContextComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Objects;
import java.util.concurrent.Executor;

/**
 * 请求处理
 *
 * @author YinShangwen
 * @since 2023/4/4 14:07
 */
@Slf4j
public class RequestHandler extends AbstractRequestHandler {
    public RequestHandler(Executor executor) {
        super(executor);
    }

    @Override
    public Object handler(Request msg) throws Exception {
        ApplicationContext context = ApplicationContextComponent.get();
        if (Objects.isNull(context)) {
            throw new RuntimeException("No initialization completed！");
        }
        Class<?> clazz = Class.forName(msg.getReferenceClassName());
        Method method = clazz.getMethod(msg.getMethodName(), msg.getParameterTypes());
        Object bean;
        if (StringUtils.hasText(msg.getBeanName())) {
            bean = context.getBean(msg.getBeanName());
        } else {
            bean = context.getBean(clazz);
        }
        RpcService rpcService = bean.getClass().getAnnotation(RpcService.class);
        if (Objects.isNull(rpcService)) {
            log.error("客户端调用了未被RpcService注解标记的bean。request：{}", msg);
            throw new RuntimeException("Illegal call");
        }
        return method.invoke(bean, msg.getArgs());
    }
}
